package blog.ideablog.controller;


import blog.ideablog.constants.JwtConstants;
import blog.ideablog.model.dto.UserDTO;
import blog.ideablog.model.vo.Results;
import blog.ideablog.service.UserService;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

@Api("与用户相关的API接口")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Results<Map<String, Object>> login(@ApiParam(name = "用户登录信息", value = "传入json格式", required = true)
                                              @RequestBody @Valid UserDTO userDTO) {
        String token = userService.checkUsernamePassword(userDTO);
        return Results.ok("登录成功", MapUtil.of("token", token));
    }

    @PostMapping("/auth/logout")
    @ApiOperation("用户注销登录")
    public Results<Object> logout(@RequestAttribute("token") String token) {
        redisTemplate.opsForSet().add(JwtConstants.REDIS_KEY, token);
        return Results.ok("退出登录成功", null);
    }


}
